package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.Session;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;

@Controller
@RequestMapping("/manage")
public class ManagementController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CatalogService catalogService;

    //管理主界面
    @GetMapping("/main")
    public String viewMain(){
        return "management/managemain";
    }

    //管理密码输入界面
    @GetMapping("/code")
    public String inputCode(){
        return "management/managerCode";
    }

    @GetMapping("/usermanagement")
    public String viewUserList(HttpSession session){
        List<String> allId = accountService.getAccountList();
        System.out.println(allId.size());
        session.setAttribute("userIdList",allId);
        return "usermanagement/userList";
    }

    @GetMapping("/userBasicInfo")
    public String userBasicInformation(@RequestParam("userId") String userId,HttpSession session){
        System.out.println(userId);
        Account account = accountService.getCommonInformation(userId);
        System.out.println(account.getUsername());
        boolean isEnglish = false;
        boolean isDogs = false;
        boolean isFish = false;
        boolean isReptiles = false;
        boolean isCat = false;
        boolean isBird = false;
        boolean notEnglish = false;
        if(account.getLanguagePreference().equals("english")){
            isEnglish = true;
        }else{
            notEnglish = true;
        }
        System.out.println(account.getFavouriteCategoryId());
        switch (account.getFavouriteCategoryId()){
            case "FISH":
                isFish = true;
                System.out.println("鱼");
                break;
            case "DOGS":
                isDogs = true;
                break;
            case "REPTILES":
                isReptiles = true;
                break;
            case "CATS":
                isCat = true;
                break;
            case "BIRDS":
                isBird = true;
                break;
        }
        session.setAttribute("baseAccount",account);
        session.setAttribute("isEnglish",isEnglish);
        session.setAttribute("notEnglish",notEnglish);
        session.setAttribute("isFish",isFish);
        session.setAttribute("isDogs",isDogs);
        session.setAttribute("isReptiles",isReptiles);
        session.setAttribute("isCat",isCat);
        session.setAttribute("isBird",isBird);
        return "usermanagement/basicInfo";
    }

    @PostMapping("/saveBasicInfo")
    public void saveBasicInfo(HttpServletResponse resp,HttpSession session,
                              @RequestParam("firstName") String firstName,
                              @RequestParam("lastName") String lastName,
                              @RequestParam("address1") String address1, @RequestParam("address2") String address2, @RequestParam("city") String city,
                              @RequestParam("state") String state, @RequestParam("zip") String zip, @RequestParam("country") String country,
                              @RequestParam("languagePreference") String languagePreference,
                              @RequestParam("favouriteCategoryId") String favouriteCategoryId) throws IOException ,Exception{
        //校验格式

        Account account = (Account) session.getAttribute("baseAccount");
        account.setFirstName(firstName);
        account.setLastName(lastName);
        account.setAddress1(address1);
        account.setAddress2(address2);
        account.setCity(city);
        account.setState(state);
        account.setZip(zip);
        account.setCountry(country);
        account.setLanguagePreference(languagePreference);
        account.setFavouriteCategoryId(favouriteCategoryId);
        accountService.updateCommonInformation(account);
        session.setAttribute("baseAccount",account);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        result.setCode(1);
        result.setMsg("edit success");
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/userSafeInfo")
    public String userSafeInformation(@RequestParam("userId") String userId,HttpSession session){
        Account account = accountService.getSafeInformation(userId);
        session.setAttribute("safeAccount",account);
        String password = account.getPassword();
        String email = account.getEmail();
        String showPassword = "";
        String[] suf = email.split("@");
        String showEmail = email.substring(0,3);
        for(int i=0;i<password.length();i++){
            showPassword = showPassword+'*';
        }
        for(int i=3;i<suf[0].length();i++){
            showEmail = showEmail + '*';
        }
        showEmail = showEmail+'@'+suf[1];
        System.out.println(showPassword);
        System.out.println(showEmail);
        session.setAttribute("showPassword",showPassword);
        session.setAttribute("showEmail",showEmail);
        return "usermanagement/safeInfo";
    }

    @PostMapping("/saveSafeInfo")
    public void saveSafeInfo(HttpServletResponse resp, HttpSession session, @RequestParam("password") String password,
                              @RequestParam("email") String email, @RequestParam("phone") String phone) throws IOException {
        Account account = (Account) session.getAttribute("safeAccount");
        account.setPassword(password);
        account.setEmail(email);
        account.setPhone(phone);
        accountService.updateSafeInformation(account);
        session.setAttribute("safeAccount",account);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        result.setCode(1);
        String showPassword = "";
        String[] suf = email.split("@");
        String showEmail = email.substring(0,3);
        for(int i=0;i<password.length();i++){
            showPassword = showPassword+'*';
        }
        for(int i=3;i<suf[0].length();i++){
            showEmail = showEmail + '*';
        }
        showEmail = showEmail+'@'+suf[1];
        System.out.println(showPassword);
        System.out.println(showEmail);
        session.setAttribute("showPassword",showPassword);
        session.setAttribute("showEmail",showEmail);
        result.setMsg(showPassword+"#"+showEmail);
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    //订单管理进入界面
    @GetMapping("/ordermanagement")
    public String viewOrderList(HttpSession session){
        List<Order> allOrder = orderService.getOrders();
        System.out.println(allOrder.size());
        session.setAttribute("orderIdList",allOrder);
        List<String> orderDate = new ArrayList<>();
        List<String> usersId = new ArrayList<>();
        for(int i=0;i<allOrder.size();i++){
            orderDate.add(allOrder.get(i).getOrderDate().toString());
            usersId.add(allOrder.get(i).getUsername());
        }
        for(int i = 0;i<orderDate.size()-1;i++) {
            for (int j = orderDate.size() - 1; j > i; j--) {
                if (orderDate.get(j).equals(orderDate.get(i))) {
                    orderDate.remove(j);
                }
            }
        }
        for(int i = 0;i<usersId.size()-1;i++) {
            for (int j = usersId.size() - 1; j > i; j--) {
                if (usersId.get(j).equals(usersId.get(i))) {
                    usersId.remove(j);
                }
            }
        }
        session.setAttribute("orderDateList",orderDate);
        session.setAttribute("usersList",usersId);
        return "ordermanagement/orderList";
    }

    //修改订单
    @PostMapping("/saveOrderInfo")
    public void saveBasicInfo(HttpServletResponse resp,HttpSession session,
                              @RequestParam("cardType") String cardType,
                              @RequestParam("creditCard") String creditCard,
                              @RequestParam("billToFirstName") String billToFirstName,
                              @RequestParam("billToLastName") String billToLastName,
                              @RequestParam("billAddress1") String billAddress1,
                              @RequestParam("billAddress2") String billAddress2,
                              @RequestParam("billCity") String billCity,
                              @RequestParam("billState") String billState,
                              @RequestParam("billZip") String billZip,
                              @RequestParam("billCountry") String billCountry,
                              @RequestParam("shipToFirstName") String shipToFirstName,
                              @RequestParam("shipToLastName") String shipToLastName,
                              @RequestParam("shipAddress1") String shipAddress1,
                              @RequestParam("shipAddress2") String shipAddress2,
                              @RequestParam("shipCity") String shipCity,
                              @RequestParam("shipState") String shipState,
                              @RequestParam("shipZip") String shipZip,
                              @RequestParam("shipCountry") String shipCountry,
                              @RequestParam("courier") String courier) throws IOException ,Exception{
        //校验格式
        System.out.println("*******");
        Order order=(Order) session.getAttribute("orderInfo");
        System.out.println("9999999999"+order.getOrderId());
        order.setCardType(cardType);
        order.setCreditCard(creditCard);
//        SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd ");
//        Date exp=formatter.parse(expiryDate);
        order.setBillToFirstName(billToFirstName);
        order.setBillToLastName(billToLastName);
        order.setBillAddress1(billAddress1);
        order.setBillAddress2(billAddress2);
        order.setBillCity(billCity);
        order.setBillState(billState);
        order.setBillZip(billZip);
        order.setBillCountry(billCountry);
        order.setShipToFirstName(shipToFirstName);
        order.setShipToLastName(shipToLastName);
        order.setShipAddress1(shipAddress1);
        order.setShipAddress2(shipAddress2);
        order.setShipCity(shipCity);
        order.setShipState(shipState);
        order.setShipZip(shipZip);
        order.setShipCountry(shipCountry);
        order.setCourier(courier);
        orderService.updatePaymentAndBillingAndShipping(order);
        session.setAttribute("orderInfo",order);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out=resp.getWriter();
        Result result=new Result();
        result.setCode(1);
        result.setMsg("edit success");
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }
    //订单退款
    @GetMapping("/reFundOrder")
    public String RefundOrder(@RequestParam("orderId") String orderId,HttpSession session){
        int orderid = Integer.parseInt(orderId);
        orderService.removeOrder(orderid);
        List<Order> orderList = orderService.getOrders();
        session.setAttribute("orderIdList",orderList);
        return "ordermanagement/orderList";
    }

    //发货
    @GetMapping("/deliverOrder")
    public  String Deliver(@RequestParam("orderId") String orderId,HttpSession session){
        int orderid = Integer.parseInt(orderId);
        orderService.removeOrder(orderid);
        List<Order> orderList = orderService.getOrders();
        session.setAttribute("orderIdList",orderList);
        return "ordermanagement/orderList";
    }

    //查询订单后的界面
    @GetMapping("/viewSelectOrder")
    public String viewSelectOrder(HttpSession session){
        return "ordermanagement/orderList";
    }
    //订单详细信息
    @GetMapping("/orderBasicInfo")
    public String viewOrderInfo(HttpSession session,int orderId){
        Order orderInfo=orderService.getOrder(orderId);
        session.setAttribute("orderInfo",orderInfo);
        return "ordermanagement/orderInfo";
    }

    //搜索订单
    @PostMapping("/searchOrder")
    public void searchOrderByUserIdOrDate(HttpSession session,HttpServletResponse resp,@RequestParam("userIdSelect") String userIdSelect,
                                          @RequestParam("dateSelect") String dateSelect) throws IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        List<Order> orderList = null;
        if(userIdSelect.length()!=0&&dateSelect.length()==0){
            orderList = orderService.getOrdersByUsername(userIdSelect);
            if(orderList==null){
                System.out.println("没有该用户的订单");
                result.setCode(0);
                result.setMsg("failed");
            }else{
                System.out.println("该用户的订单查询成功");
                result.setCode(1);
                result.setMsg("success");
            }
        }else if(userIdSelect.length()==0&&dateSelect.length()!=0){
            orderList = orderService.getOrdersByOrderdate(dateSelect);
            if(orderList==null){
                System.out.println("没有该天的订单");
                result.setCode(2);
                result.setMsg("failed");
            }else{
                System.out.println("该天的订单查询成功");
                result.setCode(3);
                result.setMsg("success");
            }
        }else if(userIdSelect.length()!=0&&dateSelect.length()!=0){
            orderList = orderService.getOrdersByUsernameAndOrderdate(userIdSelect,dateSelect);
            if(orderList==null){
                System.out.println("该用户该天无订单");
                result.setCode(4);
                result.setMsg("failed");
            }else{
                System.out.println("该用户该天的订单查询成功");
                result.setCode(5);
                result.setMsg("success");
            }
        }
        if(orderList!=null){
            session.setAttribute("orderIdList",orderList);
        }
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    //订单分析页面
    @GetMapping("/analyseOrders")
    public String analyseOrders(HttpSession session){
        List<Integer> number=new ArrayList<>();
        number.add(orderService.getNumOfOrderPriceBetweenAToB(0,100));
        number.add(orderService.getNumOfOrderPriceBetweenAToB(100,200));
        number.add(orderService.getNumOfOrderPriceBetweenAToB(200,400));
        number.add(orderService.getNumOfOrderPriceBetweenAToB(400,600));
        number.add(orderService.getNumOfOrderPriceBetweenAToB(600,1000));
        number.add(orderService.getNumOfOrderPriceBetweenAToB(1000,10000));
        session.setAttribute("orderNumber",number);
        String[][] category = orderService.getNumOfCategorySell();
        List<String> categoryNumber = new ArrayList<>();//存储种类名字
        List<String> sellNumber = new ArrayList<>();//存储种类销量
        for(int i=0;i< category[0].length;i++){
            categoryNumber.add(category[0][i]);
            sellNumber.add(category[1][i]);
        }
        session.setAttribute("categoryNumber",categoryNumber);
        session.setAttribute("sellNumber",sellNumber);
        return "ordermanagement/orderAnalyse";
    }

    @GetMapping("/intoPetManage")
    public String intoPetManage(HttpSession session){
        //查找到所有category
        List<Category> categoryList = catalogService.getCategoryList();
        session.setAttribute("categoryList",categoryList);
        System.out.println(categoryList.get(0).getCategoryId());
        return "petmanagement/categorySelectPage";
    }

    @GetMapping("/editCategory")
    public String editCategory(HttpSession session,@RequestParam("categoryId") String categoryId){
        Category category=catalogService.getCategory(categoryId);
        session.setAttribute("selectedCategory",category);
        return "petmanagement/editCategory";
    }

    @PostMapping("/saveCategory")
    public String saveCategory(HttpSession session, HttpServletResponse resp,String name,String categoryid,
                             MultipartFile imagepath)throws IOException{
        Category oldcategory =(Category) session.getAttribute("selectedCategory");
        Category category = new Category();
        category.setCategoryId(categoryid);
        category.setName(name);
        System.out.println("***"+name);
        if(!imagepath.getOriginalFilename().equals("")){
            imagepath.transferTo(new File("C:/webproject/ssm-jpetstore/src/main/resources/static/image/"+imagepath.getOriginalFilename()));
            category.setDescription("../image/"+imagepath.getOriginalFilename());
        }else{
            category.setDescription(oldcategory.getDescription());
        }
        catalogService.updateCategory(category);
        List<Category> categoryList = catalogService.getCategoryList();
        session.setAttribute("categoryList",categoryList);
        System.out.println(categoryList.get(0).getCategoryId());
        return "petmanagement/categorySelectPage";
    }

    @GetMapping("/intoProductPage")
    public String intoProductPage(HttpSession session,@RequestParam("cateid")String cateid){
        List<Product> productImg = catalogService.getProductListByCategory(cateid);
        List<Product> productDes = catalogService.getProductListByCategory(cateid);
        for(int i=0;i<productImg.size();i++){
            String temp = productImg.get(i).getDescription();
            String[] str = temp.split("\"");
            productImg.get(i).setDescription(str[1]);
        }
        for(int j=0;j<productDes.size();j++){
            String tempDes = productDes.get(j).getDescription();
            String[] strd = tempDes.split(">");
            productDes.get(j).setDescription(strd[1]);
        }
        session.setAttribute("imageProductList",productImg);//描述只获取图片
        session.setAttribute("desProductList",productDes);//描述只获取描述
        session.setAttribute("beforCategory",cateid);
        return "petmanagement/productSelectPage";
    }

    //进入item列
    @GetMapping("/intoItemPage")
    public String intoItemPage(HttpSession session,@RequestParam("productid") String productid){
        System.out.println(productid);
        List<Item> itemList = catalogService.getItemListByProduct(productid);
        Product product = catalogService.getProduct(productid);
        session.setAttribute("beforeProductId",productid);
        session.setAttribute("manageitemList",itemList);
        session.setAttribute("beforCategory",product.getCategoryId());
        return "petmanagement/intoItemSelect";
    }

    //进入item详细信息页面
    @GetMapping("/showItemDetails")
    public String showItemDetails(@RequestParam("itemId") String itemId,HttpSession session){
        Item item = catalogService.getItem(itemId);
        session.setAttribute("selectItem",item);
        List<String> allProductId = catalogService.getProductIdList();
        session.setAttribute("allProductId",allProductId);
        return "petmanagement/itemDetails";
    }

    //修改item信息
    @PostMapping("/updateItem")
    public void updateItem(HttpSession session, HttpServletResponse resp,@RequestParam("productIdSelect") String productIdSelect,
                             @RequestParam("listprice") String listprice,@RequestParam("unitcost") String unitcost,
                             @RequestParam("supplier") String supplier,@RequestParam("attr1") String attr1,
                             @RequestParam("attr2") String attr2,@RequestParam("attr3") String attr3,@RequestParam("attr4") String attr4,
                             @RequestParam("attr5") String attr5) throws IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        Item item =(Item) session.getAttribute("selectItem");
        if(productIdSelect!=null&&productIdSelect.length()!=0&&!productIdSelect.equals("")){
            item.setProductId(productIdSelect);
        }
        System.out.println(listprice);
        String list = listprice.substring(1);
        String unit = unitcost.substring(1);
        System.out.println(list);
        System.out.println(productIdSelect);
        item.setListPrice(new BigDecimal(list));
        item.setUnitCost(new BigDecimal(unit));
        item.setSupplierId(new Integer(supplier));
        item.setAttribute1(attr1);
        item.setAttribute2(attr2);
        item.setAttribute3(attr3);
        item.setAttribute4(attr4);
        item.setAttribute5(attr5);
        catalogService.updateItem(item);
        session.setAttribute("selectItem",item);
        result.setCode(1);
        result.setMsg("/manage/showItemDetails?itemId="+item.getItemId());
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/newCategoryForm")
    public String newCategory(){
        return "petmanagement/newCategory";
    }

    @PostMapping("/newCategoryIdIsExist")
    public void newCategoryIdIsExist(HttpServletResponse resp,@RequestParam("newcategoryid") String newcategoryid) throws IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        List<Category> categoryList = catalogService.getCategoryList();
        boolean isExist=false;
        for(int i=0;i<categoryList.size();i++){
            if(categoryList.get(i).getCategoryId().equals(newcategoryid)){
                isExist=true;
                break;
            }
        }
        if(isExist){
            System.out.println("1111");
            result.setCode(0);
            result.setMsg("Exist");
        }else{
            result.setCode(1);
            result.setMsg("Not Exist");
        }
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @PostMapping("/addCategory")
    public String addCategory(HttpSession session, HttpServletResponse resp,String name,String categoryid,
                            MultipartFile imagepath) throws IOException {
        Category category = new Category();
        category.setCategoryId(categoryid);
        category.setName(name);
        System.out.println(categoryid);
        System.out.println(name);
        System.out.println(imagepath);
        if(!imagepath.getOriginalFilename().equals("")&&imagepath!=null){
            System.out.println(imagepath.getOriginalFilename());
            imagepath.transferTo(new File("C:/webproject/ssm-jpetstore/src/main/resources/static/image/"+imagepath.getOriginalFilename()));
            category.setDescription("../image/"+imagepath.getOriginalFilename());
        }else{
            category.setDescription("");
        }
        catalogService.insertCategory(category);
        List<Category> categoryList = catalogService.getCategoryList();
        session.setAttribute("categoryList",categoryList);
        return "petmanagement/categorySelectPage";
    }

    @GetMapping("/deleteCategory")
    public String deleteCategory(HttpSession session,@RequestParam("categoryId") String categoryId){
        catalogService.removeCategory(categoryId);
        List<Category> categoryList = catalogService.getCategoryList();
        session.setAttribute("categoryList",categoryList);
        return "petmanagement/categorySelectPage";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("itemId")String itemid,@RequestParam("productId") String productId,HttpSession session){
        catalogService.removeItem(itemid);
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        session.setAttribute("manageitemList",itemList);
        return "petmanagement/intoItemSelect";
    }

    @GetMapping("/newItemForm")
    public String newItemForm(HttpSession session){
        List<String> productIdList = catalogService.getProductIdList();
        session.setAttribute("allProductId",productIdList);
        return "petmanagement/newItem";
    }

    @PostMapping("/addItem")
    public void addItem(HttpServletResponse resp,HttpSession session,@RequestParam("productIdSelect") String productIdSelect,
                          @RequestParam("listprice") String listprice,@RequestParam("unitcost") String unitcost,
                          @RequestParam("supplier") String supplier,@RequestParam("attr1") String attr1,
                          @RequestParam("attr2") String attr2, @RequestParam("attr3") String attr3,
                          @RequestParam("attr4") String attr4,@RequestParam("attr5") String attr5) throws IOException {
        System.out.println("456");
        String productId = (String) session.getAttribute("beforeProductId");
        Item item=new Item();
        item.setItemId(catalogService.getNewItemId());
        item.setProductId(productIdSelect);
        item.setListPrice(new BigDecimal(listprice));
        item.setUnitCost(new BigDecimal(unitcost));
        item.setSupplierId(new Integer(supplier));
        item.setAttribute1(attr1);
        item.setAttribute2(attr2);
        item.setAttribute3(attr3);
        item.setAttribute4(attr4);
        item.setAttribute5(attr5);
        catalogService.insertItem(item);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        result.setCode(1);
        result.setMsg("/manage/intoItemPage?productid="+productId);
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/presearchCategory")
    public void presearchCategory(HttpServletResponse resp,String keyword, Model model,HttpSession session) throws IOException {
        System.out.println(keyword);
        List<Category> categoryList = catalogService.searchCategoryList(keyword);
//        List<Product> productList=catalogService.searchProductList(keyword);
        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();

        JSONArray searchArray=new JSONArray();
        for(int i=0;i<categoryList.size();i++){
            //产品名字
            JSONObject searchObject=new JSONObject();
            searchObject.put("name",categoryList.get(i).getName());
            //添加到数组中
            searchArray.add(searchObject);
        }
        //转换成JSON字符串
        String str=searchArray.toJSONString();
        out.print(str);
    }

    @GetMapping("/presearchProduct")
    public void presearchProduct(HttpServletResponse resp,String keyword, Model model,HttpSession session) throws IOException {
        System.out.println(keyword);
        List<Product> productList = catalogService.searchProductList(keyword);
//        List<Product> productList=catalogService.searchProductList(keyword);
        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();

        JSONArray searchArray=new JSONArray();
        for(int i=0;i<productList.size();i++){
            //产品名字
            JSONObject searchObject=new JSONObject();
            searchObject.put("name",productList.get(i).getName());
            //添加到数组中
            searchArray.add(searchObject);
        }
        //转换成JSON字符串
        String str=searchArray.toJSONString();
        out.print(str);
    }

    @PostMapping("/searchCategory")
    public void searchCategory(HttpServletResponse resp,HttpSession session, Model model,@RequestParam("keyword") String keyword) throws IOException {
        System.out.println(keyword);
        List<Category> categoryList = catalogService.searchCategoryList(keyword);

        //保存数据
        session.setAttribute("keyword", keyword);
        session.setAttribute("categoryList", categoryList);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();

        result.setCode(11);
        result.setMsg("/manage/searchIntoCategory");
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/searchIntoCategory")
    public String searchIntoCategory(){
        return "petmanagement/categorySelectPage";
    }

    @PostMapping("/searchProductlist")
    public void searchProductlist(HttpServletResponse resp,HttpSession session, Model model,@RequestParam("keyword") String keyword) throws IOException {
        System.out.println(keyword);
        List<Product> productList = catalogService.searchProductList(keyword);
        List<Product> productImg =catalogService.searchProductList(keyword);
        for(int i=0;i<productList.size();i++){
            String temp = productList.get(i).getDescription();
            String[] str = temp.split("\"");
            productImg.get(i).setDescription(str[1]);
        }
        session.setAttribute("imageProductList",productImg);
        //保存数据
        session.setAttribute("keyword", keyword);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();

        result.setCode(11);
        result.setMsg("/manage/searchIntoProduct");
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @GetMapping("/searchIntoProduct")
    public String searchIntoProduct(HttpSession session){
        session.setAttribute("beforCategory","BIRDS");
        return "petmanagement/productSelectPage";
    }
    @GetMapping("/newProductForm")
    public String newProductForm(HttpSession session){
        List<String> allCategoryId = catalogService.getCategoryIdList();
        session.setAttribute("allCategoryId",allCategoryId);
        return "petmanagement/newProduct";
    }

    @PostMapping("/productIdIsExist")
    public void productIdIsExistInTheCategory(HttpServletResponse resp,@RequestParam("productid") String productid) throws IOException {
        List<String> productList=catalogService.getProductIdList();
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        Result result=new Result();
        boolean exist = false;
        for(int i=0;i<productList.size();i++){
            if(productList.get(i).equals(productid)){
                exist=true;
                break;
            }
        }
        if(exist){
            result.setCode(0);
            result.setMsg("exist");
        }else{
            result.setCode(1);
            result.setMsg("Not exist");
        }
        String str = JSON.toJSONString(result);
        out.print(str);
        out.flush();
        out.close();
    }

    @PostMapping("/addProduct")
    public String addProduct(HttpSession session,HttpServletResponse resp,String productid,String categoryIdSelect,
                           String name,MultipartFile imagepath,String description) throws IOException {
        System.out.println(productid);
        System.out.println(categoryIdSelect);
        System.out.println(name);
        System.out.println(imagepath);
        System.out.println(imagepath.getOriginalFilename());
        System.out.println(description);
        Product product = new Product();

        product.setProductId(productid);
        product.setCategoryId(categoryIdSelect);
        product.setName(name);
        String img=null;
        if(!imagepath.getOriginalFilename().equals("")&&imagepath!=null){
            System.out.println(imagepath.getOriginalFilename()+"123");
            imagepath.transferTo(new File("C:/webproject/ssm-jpetstore/src/main/resources/static/image/"+imagepath.getOriginalFilename()));
            img="../image/"+imagepath.getOriginalFilename();
        }else{
            img="";
        }
        String des="<image src=\""+img+"\">"+description;
        product.setDescription(des);
        catalogService.insertProduct(product);
        List<Product> productImg = catalogService.getProductListByCategory(categoryIdSelect);
        List<Product> productDes = catalogService.getProductListByCategory(categoryIdSelect);
        for(int i=0;i<productImg.size();i++){
            String temp = productImg.get(i).getDescription();
            String[] str = temp.split("\"");
            productImg.get(i).setDescription(str[1]);
        }
        for(int j=0;j<productDes.size();j++){
            String tempDes = productDes.get(j).getDescription();
            String[] strd = tempDes.split(">");
            productDes.get(j).setDescription(strd[1]);
        }
        session.setAttribute("imageProductList",productImg);//描述只获取图片
        session.setAttribute("desProductList",productDes);//描述只获取描述
        session.setAttribute("beforCategory",categoryIdSelect);
        return "petmanagement/productSelectPage";
    }

    @GetMapping("/deleteProduct")
    public String deleteProduct(HttpSession session,@RequestParam("productid") String productid){
        catalogService.removeProduct(productid);
        String categoryIdSelect=(String) session.getAttribute("beforCategory");
        List<Product> productImg = catalogService.getProductListByCategory(categoryIdSelect);
        List<Product> productDes = catalogService.getProductListByCategory(categoryIdSelect);
        for(int i=0;i<productImg.size();i++){
            String temp = productImg.get(i).getDescription();
            String[] str = temp.split("\"");
            productImg.get(i).setDescription(str[1]);
        }
        for(int j=0;j<productDes.size();j++){
            String tempDes = productDes.get(j).getDescription();
            String[] strd = tempDes.split(">");
            productDes.get(j).setDescription(strd[1]);
        }
        session.setAttribute("imageProductList",productImg);//描述只获取图片
        session.setAttribute("desProductList",productDes);//描述只获取描述
        session.setAttribute("beforCategory",categoryIdSelect);
        return "petmanagement/productSelectPage";
    }

    @GetMapping("/editProduct")
    public String editProduct(HttpSession session,@RequestParam("productId") String productId){
        Product product=catalogService.getProduct(productId);
        session.setAttribute("selectedProduct",product);
        List<String> categoryId=catalogService.getCategoryIdList();
        session.setAttribute("allcategoryId",categoryId);
        session.setAttribute("categoryNow",product.getCategoryId());
        return "petmanagement/editProduct";
    }

    @PostMapping("/saveProduct")
    public String saveProduct(HttpSession session, HttpServletResponse resp,String name,String productid,
                              MultipartFile imagepath,String descript,String categoryIdSelect)throws IOException{
        Product product=(Product) session.getAttribute("selectedProduct");
//        Product product = new Product();
        product.setProductId(productid);
        product.setName(name);
        String temp =product.getDescription();
        String[] str = temp.split("\"");
        String beforimgpath=str[1];
        String tempDes = product.getDescription();
        String[] strd = tempDes.split(">");
        String befordes=strd[1];
        String newimgpath=null;
        String newdes=null;
        String befor = product.getCategoryId();
        if(categoryIdSelect!=null&&!categoryIdSelect.equals("")){
            product.setCategoryId(categoryIdSelect);
        }
        if(!imagepath.getOriginalFilename().equals("")){
            imagepath.transferTo(new File("D:/web/ssm-jpetstore-order/src/main/resources/static/image/"+imagepath.getOriginalFilename()));
            newimgpath="../image/"+imagepath.getOriginalFilename();
        }else{
            newimgpath=beforimgpath;
        }
        if(descript.equals("")||descript==null){
            newdes=befordes;
        }else{
            newdes=descript;
        }
        String discp="<image src=\""+newimgpath+"\">"+newdes;
        product.setDescription(discp);
        catalogService.updateProduct(product);
        List<Product> productImg = catalogService.getProductListByCategory(befor);
        List<Product> productDes = catalogService.getProductListByCategory(befor);
        for(int i=0;i<productImg.size();i++){
            String temp1 = productImg.get(i).getDescription();
            String[] str1 = temp1.split("\"");
            productImg.get(i).setDescription(str1[1]);
        }
        for(int j=0;j<productDes.size();j++){
            String tempDes1 = productDes.get(j).getDescription();
            String[] strd1 = tempDes1.split(">");
            productDes.get(j).setDescription(strd1[1]);
        }
        session.setAttribute("imageProductList",productImg);//描述只获取图片
        session.setAttribute("desProductList",productDes);//描述只获取描述
        session.setAttribute("beforCategory",befor);
        return "petmanagement/productSelectPage";
    }

}
